package com.li.day.day17;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

public class Test extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("gbk");
        Connection co=null;
        PreparedStatement pp=null;
        ResultSet rr=null;
        PrintWriter writer=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            String s = "select s.studentname,AVG(score),MAX(score)from students s,result r WHERE s.studentno=r.studemtno GROUP BY s.studentno";
             co = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/p3kao", "root", "root");
             pp = co.prepareStatement(s);
             rr = pp.executeQuery();
             writer = resp.getWriter();
            while(rr.next()){
                //req.getParameter()
                 writer.write("姓名"+rr.getString(1));
                 writer.write(" 平均分"+rr.getString(2));
                 writer.write(" 最高分"+ rr.getString(3));
             }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if (writer!=null){
                writer.close();
            }
            if (rr!=null){
                try {
                    rr.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (pp!=null){
                try {
                    pp.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(co!=null){
                try {
                    co.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
